import React, { useState, useRef, useEffect } from 'react';
import { 
  View, 
  Text, 
  TextInput, 
  TouchableOpacity, 
  StyleSheet, 
  FlatList, 
  ActivityIndicator, 
  Alert, 
  Keyboard
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { FontAwesome } from '@expo/vector-icons';
import { auth } from '../utils/auth';
import { api } from '../utils/api';
import { CUSTOMER_SERVICE_API } from '../config/apiConfig';

const ChatScreen = ({ navigation }) => {
  const [messages, setMessages] = useState([]);
  const [inputMessage, setInputMessage] = useState('');
  const [isTyping, setIsTyping] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const flatListRef = useRef(null);

  // 初始化欢迎消息
  useEffect(() => {
    // 检查登录状态
    checkLoginStatus();
    
    // 添加欢迎消息
    setMessages([
      {
        id: 'welcome',
        text: '您好！我是智能客服助手，请问有什么可以帮助您的吗？',
        sender: 'bot',
        timestamp: new Date().toISOString()
      }
    ]);
  }, []);

  // 检查登录状态
  const checkLoginStatus = async () => {
    try {
      const isLoggedIn = await auth.isLoggedIn();
      if (!isLoggedIn) {
        navigation.replace('LoginScreen');
      }
    } catch (error) {
      console.error('检查登录状态失败:', error);
      navigation.replace('LoginScreen');
    }
  };

  // 发送消息
  const sendMessage = async () => {
    if (!inputMessage.trim() || isTyping) return;

    // 添加用户消息到列表
    const userMessage = {
      id: Date.now().toString(),
      text: inputMessage.trim(),
      sender: 'user',
      timestamp: new Date().toISOString()
    };

    setMessages(prevMessages => [...prevMessages, userMessage]);
    setInputMessage('');
    setIsTyping(true);

    // 滚动到底部
    setTimeout(() => {
      flatListRef.current?.scrollToEnd({ animated: true });
    }, 100);

    try {
      // 调用后端API获取回复
      const response = await api.post(CUSTOMER_SERVICE_API.CHAT, inputMessage.trim());
      
      // 添加机器人回复到列表
      const botMessage = {
        id: (Date.now() + 1).toString(),
        text: response || '抱歉，我暂时无法回答这个问题。',
        sender: 'bot',
        timestamp: new Date().toISOString()
      };

      setMessages(prevMessages => [...prevMessages, botMessage]);
    } catch (error) {
      console.error('发送消息失败:', error);
      
      // 添加错误消息到列表
      const errorMessage = {
        id: (Date.now() + 2).toString(),
        text: '抱歉，我暂时无法连接到服务器。请稍后再试。',
        sender: 'bot',
        timestamp: new Date().toISOString()
      };

      setMessages(prevMessages => [...prevMessages, errorMessage]);
    } finally {
      setIsTyping(false);
      
      // 再次滚动到底部
      setTimeout(() => {
        flatListRef.current?.scrollToEnd({ animated: true });
      }, 100);
    }
  };

  // 清除会话历史
  const clearChatHistory = async () => {
    Alert.alert(
      '清除会话历史',
      '确定要清除所有聊天记录吗？',
      [
        { text: '取消', style: 'cancel' },
        { 
          text: '确定', 
          onPress: async () => {
            setIsLoading(true);
            try {
              await api.delete(CUSTOMER_SERVICE_API.CLEAR_HISTORY);
              setMessages([]);
              // 添加新的欢迎消息
              setMessages([
                {
                  id: 'welcome-new',
                  text: '您好！我是智能客服助手，请问有什么可以帮助您的吗？',
                  sender: 'bot',
                  timestamp: new Date().toISOString()
                }
              ]);
              Alert.alert('成功', '会话历史已清除');
            } catch (error) {
              console.error('清除会话历史失败:', error);
              Alert.alert('失败', '清除会话历史失败，请稍后再试');
            } finally {
              setIsLoading(false);
            }
          },
          style: 'destructive'
        }
      ]
    );
  };

  // 处理用户登出
  const handleLogout = async () => {
    Alert.alert(
      '退出登录',
      '确定要退出登录吗？',
      [
        { text: '取消', style: 'cancel' },
        { 
          text: '确定', 
          onPress: async () => {
            try {
              await auth.logout();
              navigation.replace('LoginScreen');
            } catch (error) {
              console.error('登出失败:', error);
              Alert.alert('失败', '退出登录失败，请稍后再试');
            }
          }
        }
      ]
    );
  };

  // 渲染消息项
  const renderMessageItem = ({ item }) => {
    const isUserMessage = item.sender === 'user';
    
    return (
      <View style={[styles.messageContainer, isUserMessage ? styles.userMessageContainer : styles.botMessageContainer]}>
        <View style={[styles.messageBubble, isUserMessage ? styles.userMessageBubble : styles.botMessageBubble]}>
          <Text style={[styles.messageText, isUserMessage ? styles.userMessageText : styles.botMessageText]}>
            {item.text}
          </Text>
        </View>
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      {/* 头部 */}
      <View style={styles.header}>
        <Text style={styles.headerTitle}>智能客服</Text>
        <View style={styles.headerActions}>
          <TouchableOpacity 
            style={styles.actionButton}
            onPress={clearChatHistory}
            disabled={isLoading}
          >
            {isLoading ? (
              <ActivityIndicator size="small" color="#666" />
            ) : (
              <FontAwesome name="trash-o" size={18} color="#666" />
            )}
          </TouchableOpacity>
          
          <TouchableOpacity style={styles.actionButton} onPress={handleLogout}>
            <FontAwesome name="sign-out" size={18} color="#666" />
          </TouchableOpacity>
        </View>
      </View>

      {/* 聊天内容 */}
      <View style={styles.chatContainer}>
        <FlatList
          ref={flatListRef}
          data={messages}
          renderItem={renderMessageItem}
          keyExtractor={item => item.id}
          contentContainerStyle={styles.messageList}
          showsVerticalScrollIndicator={false}
        />

        {/* 正在输入提示 */}
        {isTyping && (
          <View style={styles.typingIndicator}>
            <ActivityIndicator size="small" color="#666" />
            <Text style={styles.typingText}>客服正在输入...</Text>
          </View>
        )}
      </View>

      {/* 输入区域 */}
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.input}
          placeholder="请输入您的问题..."
          value={inputMessage}
          onChangeText={setInputMessage}
          multiline
          maxLength={500}
          editable={!isTyping}
        />
        <TouchableOpacity 
          style={[styles.sendButton, !inputMessage.trim() && styles.sendButtonDisabled]}
          onPress={sendMessage}
          disabled={!inputMessage.trim() || isTyping}
        >
          <FontAwesome name="send" size={18} color="white" />
        </TouchableOpacity>
      </View>

      {/* 快捷问题提示 */}
      {messages.length === 1 && (
        <View style={styles.quickQuestionsContainer}>
          <Text style={styles.quickQuestionsTitle}>您可能想了解：</Text>
          <View style={styles.quickQuestionsList}>
            {['如何查看订单状态？', '商品可以退换吗？', '有什么优惠活动？'].map((question, index) => (
              <TouchableOpacity 
                key={index} 
                style={styles.quickQuestionButton}
                onPress={() => {
                  setInputMessage(question);
                  Keyboard.dismiss();
                }}
              >
                <Text style={styles.quickQuestionText}>{question}</Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>
      )}
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
    backgroundColor: 'white',
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
  },
  headerActions: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  actionButton: {
    padding: 8,
    marginLeft: 16,
  },
  chatContainer: {
    flex: 1,
    paddingHorizontal: 16,
  },
  messageList: {
    paddingVertical: 16,
  },
  messageContainer: {
    flexDirection: 'row',
    marginBottom: 16,
  },
  userMessageContainer: {
    justifyContent: 'flex-end',
    alignItems: 'flex-end',
  },
  botMessageContainer: {
    justifyContent: 'flex-start',
    alignItems: 'flex-start',
  },
  messageBubble: {
    maxWidth: '75%',
    padding: 12,
    borderRadius: 16,
  },
  userMessageBubble: {
    backgroundColor: '#007AFF',
    borderBottomRightRadius: 4,
  },
  botMessageBubble: {
    backgroundColor: 'white',
    borderWidth: 1,
    borderColor: '#eee',
    borderBottomLeftRadius: 4,
  },
  messageText: {
    fontSize: 15,
    lineHeight: 20,
  },
  userMessageText: {
    color: 'white',
  },
  botMessageText: {
    color: '#333',
  },
  typingIndicator: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 8,
    backgroundColor: 'white',
    borderRadius: 16,
    alignSelf: 'flex-start',
    marginBottom: 16,
  },
  typingText: {
    marginLeft: 8,
    fontSize: 14,
    color: '#666',
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
    backgroundColor: 'white',
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  input: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    borderRadius: 20,
    paddingHorizontal: 16,
    paddingVertical: 10,
    fontSize: 15,
    maxHeight: 100,
    textAlignVertical: 'top',
  },
  sendButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#007AFF',
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 12,
  },
  sendButtonDisabled: {
    backgroundColor: '#ccc',
  },
  quickQuestionsContainer: {
    padding: 16,
    backgroundColor: '#f8f9fa',
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  quickQuestionsTitle: {
    fontSize: 14,
    fontWeight: '500',
    color: '#666',
    marginBottom: 12,
  },
  quickQuestionsList: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
  },
  quickQuestionButton: {
    backgroundColor: 'white',
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 16,
    borderWidth: 1,
    borderColor: '#eee',
  },
  quickQuestionText: {
    fontSize: 13,
    color: '#333',
  },
});

export default ChatScreen;